package com.lsh.payment.core.service.alipay.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StreamUtil;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.internal.util.codec.Base64;
import com.lsh.payment.core.strategy.config.AliPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

/**
 * Project Name: lsh-payment
 * Created by peter on 17/3/17.
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
public class AlipayCheck {

    private static Logger logger = LoggerFactory.getLogger(AlipayCheck.class);

    public static boolean rsaCheckV2(Map<String, String> params) {

        boolean alipayRSACheckedV2;
        try {
            params.remove("sign_type");
            logger.info("开始校验");
            alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, AliPayConfig.public_key, "utf-8", AliPayConfig.sign_type_2);
            logger.info("校验结束");
        } catch (AlipayApiException e) {
            logger.error("支付宝验证回调异常", e);
            alipayRSACheckedV2 = false;
        }

        return alipayRSACheckedV2;

    }

    public static boolean rsaCheckV1(Map<String, String> params, String publicKey, String charset) {
        String sign = params.get("sign");
        String content = getSignCheckContentV1(params);

        boolean flag = false;
        try {
            flag = rsaCheckContent(content, sign, publicKey, charset);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return flag;
    }

    public static String getSignCheckContentV1(Map<String, String> params) {
        if (params == null) {
            return null;
        } else {
            params.remove("sign");
            params.remove("sign_type");
            StringBuffer content = new StringBuffer();
            ArrayList keys = new ArrayList(params.keySet());
            Collections.sort(keys);

            for (int i = 0; i < keys.size(); ++i) {
                String key = (String) keys.get(i);
                String value = (String) params.get(key);
                content.append((i == 0 ? "" : "&") + key + "=" + value);
            }

            return content.toString();
        }
    }


    public static boolean rsaCheckContent(String content, String sign, String publicKey, String charset) throws AlipayApiException {
        try {
            PublicKey e = getPublicKeyFromX509("RSA", new ByteArrayInputStream(publicKey.getBytes()));
            Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initVerify(e);
            if (StringUtils.isEmpty(charset)) {
                signature.update(content.getBytes());
            } else {
                signature.update(content.getBytes(charset));
            }

            return signature.verify(Base64.decodeBase64(sign.getBytes()));
        } catch (Exception var6) {
            throw new AlipayApiException("RSAcontent = " + content + ",sign=" + sign + ",charset = " + charset, var6);
        }
    }


    public static PublicKey getPublicKeyFromX509(String algorithm, InputStream ins) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        StringWriter writer = new StringWriter();
        StreamUtil.io(new InputStreamReader(ins), writer);
        byte[] encodedKey = writer.toString().getBytes();
        encodedKey = Base64.decodeBase64(encodedKey);
        return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
    }



//    public static void main(String[] args) {
//
//        String ds = "{\"gmt_create\":\"2020-03-19 15:15:53\",\"charset\":\"utf-8\",\"seller_email\":\"duodianjizhi@163.com\",\"subject\":\"链商订单:1240537243181907968\",\"sign\":\"eg2fi15FFQaN7qUuBN9kxlz1VVeigB0c34qwlH1GPjox7EaLPIXKVfkfU6eMvFkwGxRJxCc9pjP2BTNvagQA8rlZC46X8gL4WnrOq1Aq/hTA10YRlcuSaJx/EaspUbXUAdWc2jE/0JqCA1x+PImlTpdcEUlghIAm/CR29eJB+nCHYpY1RE5Im9zLPgVg7/fFsRoHD4W+pZODEOl8fZA8Vo+r4GoaMi5sWAjBUbAi10eboC95ZfL9ozZTRPNrZH+sZi3XDD5l4LArB0Y0zl/EF0V7BXELFT3UD9Pm9sMFWGU2TcpXeWvdHKyarWdMAi31E13/ay1+yqI6jiWSg8XlEQ==\",\"body\":\"支付宝App支付\",\"buyer_id\":\"2088402592322449\",\"invoice_amount\":\"0.02\",\"notify_id\":\"2020031900222151554022441452632625\",\"fund_bill_list\":\"[{\\\"amount\\\":\\\"0.02\\\",\\\"fundChannel\\\":\\\"PCREDIT\\\"}]\",\"notify_type\":\"trade_status_sync\",\"trade_status\":\"TRADE_SUCCESS\",\"receipt_amount\":\"0.02\",\"app_id\":\"2019121169884211\",\"buyer_pay_amount\":\"0.02\",\"sign_type\":\"RSA2\",\"seller_id\":\"2088631939425723\",\"gmt_payment\":\"2020-03-19 15:15:54\",\"notify_time\":\"2020-03-19 15:29:02\",\"version\":\"1.0\",\"out_trade_no\":\"1240537243181907968\",\"total_amount\":\"0.02\",\"trade_no\":\"2020031922001422441430030224\",\"auth_app_id\":\"2019121169884211\",\"buyer_logon_id\":\"kin***@qq.com\",\"point_amount\":\"0.00\"}";
//        Map params = JSON.parseObject(ds,Map.class);
//
//        System.out.println(rsaCheckV2(params));
//    }

}
